import { defineStore } from 'pinia'
import { ref, reactive, computed } from 'vue'
import { resetRouter } from '@/router'
import { login as loginApi, logout as logoutApi, getUserInfo as getUserInfoApi } from '@/apis'
import type { UserInfo } from '@/apis'
import { setToken, clearToken, getToken } from '@/utils/auth'
import axios from 'axios'
import { getNowDate, getRemainderTime } from '@/utils/myUtils'

const storeSetup = () => {
  const userInfo = reactive<Pick<UserInfo, 'name' | 'avatar'>>({
    name: '',
    avatar: ''
  })
  const userName = computed(() => userInfo.name)
  const avatar = computed(() => userInfo.avatar)
  const userId = ref('')

  const token = ref(getToken() || '')
  const roles = ref<string[]>([]) // 当前用户角色
  const permissions = ref<string[]>([]) // 当前角色权限标识集合

  // 当前天气信息数据
  const local = ref({
    // ip地址所在城市
    city: '',
    // 所在城市温度
    temperature: '',
    // 天气类型
    type: '',
    // 时
    hour: '',
    // 分
    minute: '',
    // 月
    month: '',
    // 日
    date: '',
    // 星期几
    day: ''
    // 出勤率echart数据
  })

  // 当前经纬度信息数据
  const location = ref({
    lat: 120.210792,
    lng: 30.246026
  })

  // 重置token
  const resetToken = () => {
    token.value = ''
    clearToken()
  }

  let resData = {}

  // 登录
  const login = async (platFormUserName?: string, platFormUserPass?: string) => {
    //console.log(platFormUserName,platFormUserPass);
    if (platFormUserName) {
      const res = await loginApi(platFormUserName, platFormUserPass)
      // resData = res
      localStorage.setItem('accessToken', res.data.accessToken)
      localStorage.setItem('userInfo', JSON.stringify(res.data))
      console.log(res)
      setToken('res.data.token')
      token.value = 'res.data.token'
      userInfo.name = res.data.platFormUserName
      console.log(res.data.platFormUserId)
      userId.value = res.data.platFormUserId
      localStorage.setItem('userId', res.data.platFormUserId)
      userInfo.avatar = 'https://d.lohand.com:1112/images/ConstantBlueCloud/WEB/icon/LOGO.png'

      // 获取当前时间
      const currentTime = getNowDate()
      // console.log(currentTime)
      localStorage.setItem('tokenSetTime', currentTime)

      if (res.data.roleName && res.data.roleName.length) {
        roles.value = ['admin']
        // permissions.value = res.data.roleCode
      } else {
        roles.value = ['ROLE_DEFAULT']
      }
    } else {
    }
  }
  // 获取当前天气的函数
  const getLocalWeather = () => {
    console.log(location)
    axios
      .get(
        `https://devapi.qweather.com/v7/weather/now?location=${ location.value.lat },${ location.value.lng }&key=1f5812a48c824dada24b4d248f4b70ab`
      )
      .then((res) => {
        console.log(res)
        local.value.temperature = res.data.now.temp
        console.log(local.value.temperature)
      })
  }

  // const

  // 退出
  const logout = async () => {
    token.value = ''
    roles.value = []
    permissions.value = []
    clearToken()
    resetRouter()
  }

  // // 获取用户信息
  const getInfo = async () => {
    let ress = localStorage.getItem('userInfo')
    // console.log(JSON.parse(ress))

    let res = JSON.parse(ress)
    // console.log(JSON.parse(res))
    userInfo.name = res.platFormUserName
    userInfo.avatar = 'https://d.lohand.com:1112/images/ConstantBlueCloud/WEB/icon/LOGO.png'
    if (res.roleName && res.roleName.length) {
      roles.value = ['admin']
      // permissions.value = res.data.permissions
    } else {
      roles.value = ['ROLE_DEFAULT']
    }
  }

  // 获取当前是早上/中午/下午/晚上
  const getTimeState = () => {
    // 获取当前时间
    let timeNow = new Date()
    // 获取当前小时
    let hours = timeNow.getHours()
    // 设置默认文字
    let text = ``
    // 判断当前时间段
    if (hours >= 0 && hours <= 10) {
      text = `早上好`
    } else if (hours > 10 && hours <= 14) {
      text = `中午好`
    } else if (hours > 14 && hours <= 18) {
      text = `下午好`
    } else if (hours > 18 && hours <= 24) {
      text = `晚上好`
    }
    // 返回当前时间段对应的状态
    return text
  }

  return {
    userInfo,
    userName,
    userId,
    avatar,
    token,
    roles,
    permissions,
    login,
    logout,
    resetToken,
    getInfo,
    getTimeState,
    getLocalWeather
  }
}

export const useUserStore = defineStore('user', storeSetup, { persist: { paths: ['token'], storage: localStorage } })
